package blacknWhite.MarketSalesMonitor;

import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.view.View;
import android.widget.ArrayAdapter;
import blacknWhite.Libraries.Utils;

import com.nullwire.trace.ExceptionHandler;

public class MarketSalesMonitorService extends Service {


	@Override
	public void onStart(Intent intent, int startId) {
		handleStart();
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		return START_STICKY;
	}

	void handleStart() {
		try {
			getMonitorProcessor().adapterOrders = new ArrayAdapter<View>(
					MarketSalesMonitorService.this, 0) {
				@Override
				public void notifyDataSetChanged() {
					// super.notifyDataSetChanged();
					getMonitorProcessor()
							.NotifyAndScheduleNextNewOrderNotification();
				}
			};

			getMonitorProcessor().adapterComments = new ArrayAdapter<View>(
					MarketSalesMonitorService.this, 0) {
				@Override
				public void notifyDataSetChanged() {
					getMonitorProcessor()
							.NotifyAndScheduleNextNewCommentNotification();
				}
			};

			getMonitorProcessor().startservice();
		} catch (Throwable e) {
			Utils.LogException(e);
		}
	}

	public static Intent GetIntent() {
		if (serviceIntent == null) {
			serviceIntent = new Intent();
			serviceIntent.setAction("blacknWhite.MarketSalesMonitorService");
		}
		return serviceIntent;
	}

	private static Intent serviceIntent;

	@Override
	public IBinder onBind(Intent arg0) {
		// TODO Auto-generated method stub
		return null;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Service#onCreate()
	 */
	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();

		if (Utils.handler == null)
			Utils.handler = new Handler();
		ExceptionHandler.register(MarketSalesMonitorService.this,
				"http://blacknwhitedev.com/stack-trace");
	}

	private MonitorProcessor monitorProcessor;

	MonitorProcessor getMonitorProcessor() {
		if (monitorProcessor == null)
			monitorProcessor = new MonitorProcessor(
					MarketSalesMonitorService.this);
		return monitorProcessor;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Service#onDestroy()
	 */
	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		if (getMonitorProcessor() != null)
			getMonitorProcessor().onDestroy();
	}

}
